package com.cipe.cmrs.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.cipe.cmrs.model.ActionableAlertsMessage;
import com.cipe.cmrs.model.User;
import com.cipe.cmrs.model.UserPreference;
import com.cipe.cmrs.util.UserUtil;
import com.cipe.cmrs.util.Util;

/**
 * @author krishna The service class to Actionable Alerts message
 */
@Service
public class ActionableAlertMesageService extends
		BaseService<ActionableAlertsMessage> {
	/**
	 * This method is not going to use no more as it's return all the Actionable message.
	 * We can delete this one
	 * @return
	 */
	public List<ActionableAlertsMessage> getAllActionableAlert() {
		return this.dao
				.getResultList("SELECT c FROM ActionableAlertsMessage c "
						+ Util.createOrderByAsc("c.actionableAlert.type"));
	}

	/**
	 * Need to Sorted according to date.
	 * If the actionableAlert content null value then it's return all the ActionableAlertMessage.
	 * @param actionableAlert
	 * @return
	 */
	public List<ActionableAlertsMessage> getAllActionableAlert(
			UserPreference userPreference) {
	    List<ActionableAlertsMessage> actionableAlertsMessages = new ArrayList<ActionableAlertsMessage>();
		String datecondition = "";
		Calendar calendar = Calendar.getInstance();
		Timestamp timestamp = new Timestamp(new Date().getTime());
		if (userPreference.getAaDateid() != null) {
			if (2 == userPreference.getAaDateid()) {
				calendar.set(Calendar.HOUR_OF_DAY, 0);
				calendar.set(Calendar.MINUTE, 0);
				calendar.set(Calendar.SECOND, 0);
				calendar.set(Calendar.MILLISECOND, 0); 
				datecondition = Util.createRangeQueryClause("c.date",
						new Timestamp(calendar.getTimeInMillis()), timestamp);
			} else if (3 == userPreference.getAaDateid()) {
				calendar.add(Calendar.DATE, -7);
				datecondition = Util.createRangeQueryClause("c.date",
						new Timestamp(calendar.getTimeInMillis()), timestamp);
			} else if (4 == userPreference.getAaDateid()) {
				calendar.add(Calendar.DATE, -30);
				datecondition = Util.createRangeQueryClause("c.date",
						new Timestamp(calendar.getTimeInMillis()), timestamp);
			}
		}
		String userCondition="";
		if(userPreference.getAaAsignId() !=null){
			userCondition=" and ( c.programOfficer="+userPreference.getAaAsignId()+" or c.regionaldirector="+userPreference.getAaAsignId()
			+" or c.programAssistant="+userPreference.getAaAsignId()+")";
		}
		
        StringBuilder filterTypeCondition = new StringBuilder();
        if (userPreference.getAaid() != null && userPreference.getAaid() > 0) {
            filterTypeCondition.append(Util.createQueryClause("c.actionableAlert.id", userPreference.getAaid()));
        } else {
            User user = UserUtil.INSTANCE.getCurrentUser();
            Map<String, Map<String, String>> allowedUiElementsMap = user.getAllowedUiElementsMap();
            // TODO: Need "Actionable Alerts" key into  constants or property file
            Map<String, String> allowedActionableAlerts = allowedUiElementsMap.get("Actionable Alerts");
            if (allowedActionableAlerts != null && allowedActionableAlerts.size() > 0) {
                List<String> actionableTypes = new ArrayList<String>(allowedActionableAlerts.keySet());
                int i = 0;
                filterTypeCondition.append(" AND (");
                for (; i < actionableTypes.size() - 1; i++) {
                    filterTypeCondition.append("c.actionableAlert.type = '" + actionableTypes.get(i) + "' OR ");
                }
                filterTypeCondition.append("c.actionableAlert.type = '" + actionableTypes.get(i) + "')");
            }
        }
        if(filterTypeCondition.length() > 0) {
    		String query = "SELECT c FROM ActionableAlertsMessage c where 1=1 and c.actionableAlert.id not in (7,8,12)"
    				+  filterTypeCondition.toString() + datecondition +
    						Util.createQueryClause("c.region",userPreference.getAaReagionId())+
    						userCondition
    				+ Util.createOrderByDesc("c.date");
    		actionableAlertsMessages=this.dao.getResultList(query);
    		/**
    		 * For geeting the ActionabaleAlert related to Payment Request
    		 * As payment have no reagion id 
    		 */
    		query = "SELECT c FROM ActionableAlertsMessage c where 1=1 and c.actionableAlert.id in (7,8)"
    			+ filterTypeCondition.toString() + datecondition+
    					userCondition
    			+ Util.createOrderByDesc("c.date");
    		actionableAlertsMessages.addAll(this.dao.getResultList(query));
    		/**
    		 * For geeting the ActionabaleAlert related Donoraward
    		 * As Donoraward has no filter criteria.
    		 */
    		query = "SELECT c FROM ActionableAlertsMessage c where 1=1 and c.actionableAlert.id =12"
    			+ filterTypeCondition.toString() +datecondition
    			+ Util.createOrderByDesc("c.date");
    		actionableAlertsMessages.addAll(this.dao.getResultList(query));
        }
		return actionableAlertsMessages;
	}
}
